<template>
  <h3>二三维视图联动效果</h3>
  <div class="about">
    <div id="view2"></div>
    <div id="view3"></div>
  </div>
</template>

<script setup>
import { onMounted } from "vue";
import Map from "@arcgis/core/Map";
import MapView from "@arcgis/core/views/MapView";
import SceneView from "@arcgis/core/views/SceneView.js";
import FeatureLayer from "@arcgis/core/layers/FeatureLayer.js";

/**
 * Map: 存放所有图层
 * MapView： 显示2d图层，并且图层的事件和配置都写在里面（即负责用户的交互）
 * SceneView: 3D视图类
 * FeatureLayer: 要素图层类（图层上面的细节样式）
 */

let 
  mymap2 = null,
  mymap3 = null,
  myview2 = null, // 展示2维视图
  myview3 = null, // 展示3维视图
  active, // 存放当前选中激活的视图
  views = [];

// const layer = new FeatureLayer({
//   url: "https://sampleserver6.arcgisonline.com/arcgis/rest/services/USA/MapServer/0",
// });

onMounted(() => {
  initMap();
});

// 初始化地图
const initMap = () => {
  mymap3 = new Map({
    basemap: "satellite", 
  });
  mymap2 = new Map({
    basemap: "terrain", 
  });

  // 2维视图的逻辑-------------------------------------------------------------------
  myview2 = new MapView({
    container: "view2", // 挂载在那个DOM
    map: mymap2, // 绑定的map对象
    // center: [113.5, 23.2], // 设置视图的中心点
    // zoom: 8, // 设置视图初始的缩放级别
  });


  // 3维视图的逻辑--------------------------------------------------------------------------
  myview3 = new SceneView({
    container: "view3", // 挂载在那个DOM
    map: mymap3, // 绑定的map对象
    // center: [113.5, 23.2], // 设置视图的中心点
    // zoom: 8, // 设置视图初始的缩放级别
  });


  // 遍历两种视图
  views = [myview2, myview3];
  for (const view of views) {
    // 监听视图是否正在与用户交互，例如拖动和旋转或者动画
    // interacting：当前是否在跟用户交互是则返回true     animation：是否在执行动画效果
    view.watch(["interacting", "animation"], () => {
      active = view; // 把本视图作为当前激活视图
      changeEvent(active); // 对当前执行视图执行sync方法
    });
    // 监听视点变化时不将本视图作为激活视图
    view.watch("viewpoint", () => {
      changeEvent(view);
    });
  }

  //when方法： 进入页面初始化完成的时候会自动执行里面的函数myview3.goTo， goTo即到达某个坐标或者默认的缩放大小
  myview2.when(() => {
    myview3.goTo({
      target: [113.5, 23.2],
      zoom: 7,
    });
  });
};

  // 把激活的视图点动态传给未激活视图，实现实时联动
  // 如果当前存在激活视图，则执行下面语句
 let changeEvent = (source) => {
    if (source !== active || !active || !active.viewpoint) {
      return;
    }
    for (const view of views) {
      // 将激活视图的中心点，传递给不激活的,从而实现联动
      if (view !== active) {
        view.viewpoint = active.viewpoint;
      }
    }
  };
</script>

<style scoped>
.about {
  height: 80vh;
  display: flex;
  align-items: center;
  /* flex-direction: column; */
}
.about div:nth-child(1) {
  width: 50%;
  min-height: 80vh;
  /* border: 1px solid teal; */
}
.about div:nth-child(2) {
  width: 50%;
  min-height: 80vh;
  /* border: 1px solid teal; */
}
</style>
